package cn.mrlong.tools.util

import cn.mrlong.tools.constant.PluginConstant
import com.intellij.ide.DataManager
import com.intellij.ide.plugins.PluginManager
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.extensions.PluginId
import java.awt.Desktop
import java.io.File
import java.io.IOException
import java.net.URI
import java.net.URISyntaxException
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.nio.file.StandardCopyOption

object OpenHtmlFileInBrowser {
    const val PERFETTO_URL: String = "https://ui.perfetto.dev/"

    fun openFileOrUrl(filePathOrUrl: String) {
        if (filePathOrUrl.startsWith("http://") || filePathOrUrl.startsWith("https://") || filePathOrUrl.startsWith("www.")) {
            openUrl(filePathOrUrl)
        } else {
//            var pluginId = PluginId.getId("com.your.company.unique.plugin.id");
//            val plugin = PluginManager.getPlugin(pluginId);
//            val path = plugin?.path;
//            println(plugin?.pluginPath)
//            val pluginPath = path?.absolutePath;
//
//            val sourcePath: Path = Paths.get(DataManager.getInstance().getDataContext().pa + "cn/mrlong/tools/util/winscope.html")
//            println(sourcePath.toAbsolutePath().toString())
//            Files.copy(
//                sourcePath,
//                PluginConstant.TEMP_IMAGE_DIRECTORY_PATH.toAbsolutePath(),
//                StandardCopyOption.REPLACE_EXISTING
//            );
//
//            openHtmlFile(filePathOrUrl)
        }
    }

    fun openHtmlFile(filePath: String?) {
        val file = File(filePath)
        try {
            if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
                Desktop.getDesktop().browse(file.toURI())
            } else {
                openDefaultBrowser(file.toURI())
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    fun openUrl(url: String?) {
        try {
            val uri = URI(url)
            if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
                Desktop.getDesktop().browse(uri)
            } else {
                openDefaultBrowser(uri)
            }
        } catch (e: IOException) {
            e.printStackTrace()
        } catch (e: URISyntaxException) {
            e.printStackTrace()
        }
    }

    fun openDefaultBrowser(uri: URI?) {
        try {
            if (Desktop.isDesktopSupported()) {
                Desktop.getDesktop().browse(uri)
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }
}
